package com.tianxin.workbao.workBao.Activity;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.cardview.widget.CardView;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.Role;
import com.tianxin.workbao.workBao.bean.User;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.dataProvide.RoleProvide;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.utils.common.ToastUtils;
import com.tianxin.workbao.workBao.view.MyGridView;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by hacker on 2017/6/20.
 */

public class StaffDetailActivity extends BaseActivity implements UpdateListViewListener {

    private CircleImageView header;
    private TextView name;
    private TextView phone;
    private TextView organization;
    private TextView roleTitleTv;
    private FloatingActionButton mFAb;
    private MyGridView gridView;
    private CardView cardView;
    private User mUser;
    private RoleProvide roleProvide;
    private List<Role> roleList = new ArrayList<>();
    BaseAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.staff_detail);
        super.initStatusBar(true);
        Bundle bundle = getIntent().getExtras();
        mUser = (User) bundle.getSerializable("userInfo");
        initView();
        initData();
        initEvent();
        bindView();
    }

    public void initView() {
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle(mUser.getName());
        mToolbar.setNavigationIcon(AppCompatResources.getDrawable(this, R.drawable.ic_action_back_24dp));
        setSupportActionBar(mToolbar);
        mFAb = (FloatingActionButton) findViewById(R.id.staff_detail_fab);
        header = (CircleImageView) findViewById(R.id.staff_detail_header);
        name = (TextView) findViewById(R.id.staff_detail_name);
        phone = (TextView) findViewById(R.id.staff_detail_phone);
        organization = (TextView) findViewById(R.id.staff_detail_organization);
        gridView = (MyGridView) findViewById(R.id.role_gridView);
        gridView.setNumColumns(GridView.AUTO_FIT);
        gridView.setVerticalSpacing(2);
        gridView.setHorizontalSpacing(4);
        cardView = (CardView) findViewById(R.id.role_cardView);
        roleTitleTv = (TextView) findViewById(R.id.role_title);
    }

    @Override
    public void initData() {
        getRoleList();
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return roleList.size();
            }

            @Override
            public Object getItem(int i) {
                return roleList.get(i);
            }

            @Override
            public long getItemId(int i) {
                return roleList.get(i).getId();
            }

            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                view = getLayoutInflater().inflate(R.layout.select_item, viewGroup, false);
                TextView roleNameTv = (TextView) view.findViewById(R.id.plate_number);
                roleNameTv.setText(roleList.get(i).getName());
                return roleNameTv;
            }
        };
    }

    @Override
    public void initEvent() {
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StaffDetailActivity.this.finish();
            }
        });

        mFAb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String telNumber = mUser.getMobiletel();
                if (!Pattern.matches(Constant.MOBILE_REGEX, telNumber)) {
                    getSweetAlertDialog(StaffDetailActivity.this).showError(getResources().getString(R.string.alert_info), getString(R.string.phone_number_error));
                    return;
                }
                //调用系统拨打电话
                Intent tellIntent = new Intent();
                tellIntent.setAction("android.intent.action.DIAL");
                tellIntent.setData(Uri.parse("tel:" + telNumber));
                startActivity(tellIntent);
            }
        });
    }

    @Override
    public void bindView() {
        name.setText(mUser.getName());
        phone.setText(formatPhoneNumber(mUser.getMobiletel()));
        organization.setText(mUser.getPorgname() + " " + mUser.getOrgname());
        if (mUser.getHeadphoto().length() > 3) {
            Glide.with(this).load(mUser.getHeadphoto()).asBitmap().into(header);
        }
        gridView.setAdapter(adapter);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_staff_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.staff_save) {
            try {
                AddContact();
            } catch (Exception e) {
                getSweetAlertDialog(StaffDetailActivity.this).showError(getString(R.string.alert_info), getString(R.string.save_failure));
                e.printStackTrace();
            }
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 向通讯录添加联系人
     *
     * @throws Exception
     */
    public void AddContact() throws Exception {
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = getContentResolver();
        ContentValues values = new ContentValues();
        long contactid = ContentUris.parseId(resolver.insert(uri, values));
        // 添加姓名
        uri = Uri.parse("content://com.android.contacts/data");
        values.put("raw_contact_id", contactid);
        values.put("mimetype", "vnd.android.cursor.item/name");
        values.put("data2", mUser.getPorgname() + " " + mUser.getName());
        resolver.insert(uri, values);

        // 添加电话
        values.clear();
        values.put("raw_contact_id", contactid);
        values.put("mimetype", "vnd.android.cursor.item/phone_v2");
        values.put("data2", "2");
        values.put("data1", mUser.getMobiletel());
        resolver.insert(uri, values);

        getSweetAlertDialog(StaffDetailActivity.this).showSuccess(getResources().getString(R.string.alert_info), getString(R.string.save_success));
    }

    public RoleProvide getRoleProvide() {
        if (roleProvide == null) {
            roleProvide = new RoleProvide(this, this);
        }
        return roleProvide;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void showMessage(String msg) {
        ToastUtils.showLong(msg);
    }

    @Override
    public void showProgress() {
        getSweetAlertDialog(this).showDialog("", 1200);
    }

    @Override
    public void hideProgress() {
        getSweetAlertDialog(this).dismiss();
    }

    @Override
    public void onRefreshData(Object result) {
        if (result instanceof List && !((List) result).isEmpty()) {
            roleList = (List<Role>) result;
            Log.d(TAG, "onRefreshData: "+roleList.size());
            adapter.notifyDataSetChanged();
            if (roleList != null && !roleList.isEmpty()) {
                cardView.setVisibility(View.VISIBLE);
                roleTitleTv.setText(mUser.getName() + " 拥有的角色");
            }
        }
    }

    @Override
    public void onLoadMoreData(Object result) {

    }

    public void getRoleList() {
        getRoleProvide().getDatasByUserid(mUser.getId());
    }
}
